package com.example.springboot_demo_redis_annotation_token.service.impl;

import com.example.springboot_demo_redis_annotation_token.common.Constant;
import com.example.springboot_demo_redis_annotation_token.common.ResponseCode;
import com.example.springboot_demo_redis_annotation_token.common.ServerResponse;
import com.example.springboot_demo_redis_annotation_token.exception.ServiceException;
import com.example.springboot_demo_redis_annotation_token.service.TokenService;
import com.example.springboot_demo_redis_annotation_token.util.JedisUtil;
import com.example.springboot_demo_redis_annotation_token.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_NAME = "token";

    @Autowired
    private JedisUtil jedisUtil;

    /**
     * 创建token
     * @return
     */
    @Override
    public ServerResponse createToken() {
        String str = RandomUtil.UUID32();
        StrBuilder token = new StrBuilder();
        token.append(Constant.Redis.TOKEN_PREFIX).append(str);
        //改为2分钟过期
        jedisUtil.set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE*2);

        return ServerResponse.success(token.toString(),"过期时间:"+Constant.Redis.EXPIRE_TIME_MINUTE*2);
    }

    /**
     * 检查token
     * @param request
     */
    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        //System.out.println("----getHeader token = " + token);
        if (StringUtils.isEmpty(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            //System.out.println("----getParameter token = " + token);
            if (StringUtils.isEmpty(token)) {// parameter中也不存在token
                throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
        }

        if (!jedisUtil.exists(token)) {
            //System.out.println("----redis中已经不存在此token = " + token);
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getCode(),
                    ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
        /*try {//暂停半秒钟模拟产生并发
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        Long del = jedisUtil.del(token);
        System.out.println("----del = " + del);
        //这个判断必须有,否则会有并发问题
        if (del <= 0) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
    }

}
